package serova.valeriya.electricity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.log4j.Logger;

public class Registrator implements Worker {
	
	private static final Input input = new Input();
	private static final Logger LOGGER = Logger.getLogger(Registrator.class);	
	@Override
	public void run() {
		UserDialog.printReport(UserDialog.getAboutProgram());
		UserDialog.printReport(UserDialog.getChooseCategory());				
		input.setCategory(UserDialog.getString());
		UserDialog.printReport(UserDialog.getPreviousRegistrationRequest());				
		input.setPreviousRegistration(UserDialog.getInteger());
		PrintWriter object = getPrintWriter(getRegistrationDataPath());				
		try {
			writeToFileTheFirstLaunchingData(input, object);
		} catch (IOException e) {
			String fileName = getRegistrationDataPath();
			LOGGER.error("Проблема при работе с файлом" +  fileName , e);
			UserDialog.printErrorMessage("Проблема при работе с файлом" +  fileName + e + "n/Обратитесь к администратору");	
		}
	}

	@Override
	public boolean isReady() {
		return (null != getRegistrationDataPath()) && !DataStore.getCurrentInstance().isAvailable();
	}

	private String getRegistrationDataPath() {
		return Configuration.getCurrentInstance().getRegistrationDataPath();
	}

	private static PrintWriter getPrintWriter(String fileName) {
		PrintWriter object = null;
	try {
			File file = new File(fileName);
			FileOutputStream fos = new FileOutputStream(file);
			object = new PrintWriter (fos, true); 				
		} catch (IOException e){
			LOGGER.error("Проблема при работе с файлом" +  fileName, e);
			UserDialog.printErrorMessage("Проблема при работе с файлом" +  fileName + e + "n/Обратитесь к администратору");			  
			
		}
		return object;
	}
	
	private static void writeToFileTheFirstLaunchingData(Input input, PrintWriter object) throws IOException {
		object.println (input.getCategory());
		object.println (input.getPreviousRegistration());		
		object.close();					
	}
}



